package com.huaweicloud.sdk.iot.huaweiiotsdk

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.huaweicloud.sdk.iot.device.client.requests.Command
import com.huaweicloud.sdk.iot.device.client.requests.DeviceMessage
import com.jackiepenghe.huaweimqttlibrary.DebugUtil
import com.jackiepenghe.huaweimqttlibrary.MqttManager
import com.jackiepenghe.huaweimqttlibrary.listeners.OnDeviceCommandListener
import com.jackiepenghe.huaweimqttlibrary.listeners.OnDeviceConnectListener
import com.jackiepenghe.huaweimqttlibrary.listeners.OnDeviceMessageDownListener

class MainActivity : AppCompatActivity() {

    companion object {
        private val TAG = MainActivity::class.simpleName ?: "MainActivity"

        private const val SERVICE_URL = "2e0216371e.st1.iotda-device.cn-east-3.myhuaweicloud.com"
        private const val DEVICE_ID = "And10_000000000001"
        private const val DEVICE_SECRET = "6117561367"
    }

    private val onDeviceCommandListener = object : OnDeviceCommandListener {
        override fun onDeviceCommand(requestId: String, command: Command) {
            DebugUtil.logOut(TAG, "requestId $requestId command = $command")
        }

    }
    private val onDeviceMessageDownListener = object : OnDeviceMessageDownListener {
        override fun onDeviceMessageDownListener(deviceMessage: DeviceMessage) {
            DebugUtil.logOut(TAG, "deviceMessage $deviceMessage")
        }

    }
    private val onDeviceConnectListener = object : OnDeviceConnectListener {
        override fun connectSucceed() {
            Log.w(TAG, "connectSucceed: ")
        }

        override fun connectFailed(errorMsg: String) {
            Log.w(TAG, "connectError: $errorMsg")
        }

        override fun disconnect(errorMsg: String) {
            Log.w(TAG, "disconnect: $errorMsg")
        }

        override fun reconnect() {
            Log.w(TAG, "reconnect")
            MqttManager.connect(SERVICE_URL, DEVICE_ID, DEVICE_SECRET)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MqttManager.setOnDeviceConnectListener(onDeviceConnectListener)
        MqttManager.setOnDeviceMessageDownListener(onDeviceMessageDownListener)
        MqttManager.setOnDeviceCommandListener(onDeviceCommandListener)
        MqttManager.connect(SERVICE_URL, DEVICE_ID, DEVICE_SECRET)
    }
}